<template>
	<!-- 选择城市 -->
	<CustomNavbar>
		<view class="navbar-content">
			<!-- 左侧返回按钮 -->
			<view class="nav-left" @click="goBack">
				<text class="back-icon">‹</text>
			</view>
			<!-- 中间标题 -->
			<view class="nav-title">选择城市</view>
			<!-- 右侧图标 -->
			<view class="nav-right">
				<text class="nav-icon-dots">⋯</text>
				<view class="nav-divider"></view>
				<view class="nav-icon-target">
					<view class="target-outer"></view>
					<view class="target-inner"></view>
				</view>
			</view>
		</view>
	</CustomNavbar>

	<!-- 当前定位区域 -->
	<view class="current-location-section">
		<text class="location-label">当前定位:</text>
		<text class="location-city">{{ currentCity }}</text>
		<view class="relocate-btn" @click="relocate">
			<text class="relocate-icon">↻</text>
			<text class="relocate-text">重新定位</text>
		</view>
	</view>

	<!-- 主要内容区域 -->
	<view class="content-section">
		<!-- 热门城市 -->
		<view class="popular-cities-section">
			<text class="section-title">热门城市</text>
			<view class="cities-grid">
				<view 
					class="city-tag" 
					:class="{ 'city-tag-selected': selectedCity === city }"
					v-for="(city, index) in popularCities" 
					:key="index"
					@click="handleCityClick(city)"
				>
					{{ city }}
				</view>
			</view>
		</view>

		<!-- 按字母排序的城市列表 -->
		<view class="cities-list-section">
			<view 
				class="city-group" 
				v-for="(group, letter) in cityGroups" 
				:key="letter"
			>
				<text class="group-letter">{{ letter }}</text>
				<view class="city-items">
					<view 
						class="city-item" 
						:class="{ 'city-item-selected': selectedCity === city }"
						v-for="(city, index) in group" 
						:key="index"
						@click="handleCityClick(city)"
					>
						<text class="city-name" :class="{ 'city-name-selected': selectedCity === city }">{{ city }}</text>
						<view class="city-divider"></view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 确认选择按钮（固定在底部） -->
		<view class="confirm-section-list" v-if="selectedCity">
			<button class="confirm-btn" @click="confirmSelection">确认选择</button>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted } from 'vue'
	import CustomNavbar from '@/components/CustomNavbar.vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { saveLocation, getLocation } from '@/utils/location.js'

	// 当前城市
	const currentCity = ref('焦作市')
	
	// 选中的城市
	const selectedCity = ref('')

	// 热门城市列表
	const popularCities = ref([
		'北京市', '上海市', '广州市', '深圳市',
		'杭州市', '南京市', '武汉市', '成都市',
		'西安市', '重庆市', '天津市', '苏州市'
	])

	// 所有城市数据（按字母分组）
	const allCities = {
		'A': ['安庆市', '安阳市', '安顺市', '鞍山市', '安康市', '阿克苏市', '阿勒泰市'],
		'B': ['北京市', '保定市', '包头市', '蚌埠市', '本溪市', '白山市', '白城市'],
		'C': ['长沙市', '成都市', '重庆市', '长春市', '常州市', '沧州市', '承德市', '赤峰市'],
		'D': ['大连市', '大同市', '丹东市', '大庆市', '东营市', '东莞市', '德阳市'],
		'E': ['鄂尔多斯市', '恩施市'],
		'F': ['福州市', '佛山市', '抚顺市', '阜阳市', '阜新市'],
		'G': ['广州市', '贵阳市', '桂林市', '赣州市', '广安市', '广元市'],
		'H': ['杭州市', '合肥市', '哈尔滨市', '海口市', '呼和浩特市', '邯郸市', '衡阳市', '黄山市', '惠州市'],
		'J': ['济南市', '焦作市', '吉林市', '九江市', '江门市', '揭阳市', '金华市'],
		'K': ['昆明市', '开封市', '克拉玛依市'],
		'L': ['兰州市', '拉萨市', '洛阳市', '漯河市', '柳州市', '廊坊市', '六安市'],
		'M': ['绵阳市', '眉山市', '牡丹江市'],
		'N': ['南京市', '南宁市', '南阳市', '内江市', '宁波市', '南充市'],
		'P': ['平顶山市', '盘锦市', '莆田市'],
		'Q': ['青岛市', '泉州市', '秦皇岛市', '齐齐哈尔市'],
		'R': ['日照市'],
		'S': ['上海市', '深圳市', '苏州市', '沈阳市', '石家庄市', '汕头市', '韶关市', '绍兴市', '宿迁市'],
		'T': ['天津市', '太原市', '唐山市', '泰安市', '台州市', '通辽市'],
		'W': ['武汉市', '温州市', '无锡市', '乌鲁木齐市', '梧州市', '威海市', '渭南市'],
		'X': ['西安市', '厦门市', '西宁市', '徐州市', '新乡市', '信阳市', '许昌市', '咸阳市', '襄阳市'],
		'Y': ['郑州市', '周口市', '驻马店市', '株洲市', '珠海市', '肇庆市', '淄博市', '张家口市'],
		'Z': ['郑州市', '周口市', '驻马店市', '株洲市', '珠海市', '肇庆市', '淄博市', '张家口市']
	}

	// 按字母分组的城市
	const cityGroups = computed(() => {
		return allCities
	})

	// 返回按钮
	const goBack = () => {
		uni.navigateBack()
	}

	// 重新定位
	const relocate = () => {
		uni.showLoading({
			title: '定位中...'
		})

		uni.getLocation({
			type: 'wgs84',
			success: (res) => {
				// 逆地理编码获取城市信息
				reverseGeocode(res.latitude, res.longitude)
			},
			fail: (err) => {
				uni.hideLoading()
				console.error('定位失败：', err)
				uni.showToast({
					title: '定位失败，请检查定位权限',
					icon: 'none'
				})
			}
		})
	}

	// 逆地理编码
	const reverseGeocode = (latitude, longitude) => {
		const key = 'EJABZ-ZBULT-UFMXD-VT6JM-I37RS-OZFVN'
		const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}&get_poi=1`

		uni.request({
			url: url,
			method: 'GET',
			success: (res) => {
				uni.hideLoading()
				if (res.statusCode === 200 && res.data.status === 0) {
					const result = res.data.result
					const city = result.address_component?.city || '未知城市'
					currentCity.value = city
					
					// 保存位置信息
					const locationData = {
						latitude: latitude,
						longitude: longitude,
						address: result.address || '',
						city: city,
						province: result.address_component?.province || '',
						district: result.address_component?.district || ''
					}
					saveLocation(locationData)
					
					uni.showToast({
						title: '定位成功',
						icon: 'success'
					})
				} else {
					uni.showToast({
						title: '获取位置信息失败',
						icon: 'none'
					})
				}
			},
			fail: (err) => {
				uni.hideLoading()
				console.error('逆地理编码失败：', err)
				uni.showToast({
					title: '获取位置信息失败',
					icon: 'none'
				})
			}
		})
	}

	// 点击城市（仅选中，不立即跳转）
	const handleCityClick = (cityName) => {
		selectedCity.value = cityName
	}
	
	// 确认选择城市
	const confirmSelection = () => {
		if (!selectedCity.value) {
			uni.showToast({
				title: '请先选择城市',
				icon: 'none'
			})
			return
		}
		
		// 根据城市名获取对应的经纬度
		const defaultLocation = getCityLocation(selectedCity.value)
		
		const locationData = {
			latitude: defaultLocation.latitude,
			longitude: defaultLocation.longitude,
			address: '',
			city: selectedCity.value,
			province: '',
			district: ''
		}
		
		// 保存位置信息
		saveLocation(locationData)
		currentCity.value = selectedCity.value
		
		uni.showToast({
			title: `已选择${selectedCity.value}`,
			icon: 'success'
		})

		// 延迟跳转到首页
		setTimeout(() => {
			// 使用 reLaunch 跳转到首页（适用于所有平台）
			uni.reLaunch({
				url: '/pages/index/index',
				success: () => {
					// 通知首页更新位置
					uni.$emit('locationUpdated', locationData)
				},
				fail: (err) => {
					console.error('跳转失败：', err)
					// 如果 reLaunch 失败，尝试使用 switchTab（适用于有 tabBar 的平台）
					uni.switchTab({
						url: '/pages/index/index',
						success: () => {
							uni.$emit('locationUpdated', locationData)
						}
					})
				}
			})
		}, 1000)
	}

	// 获取城市默认位置（这里可以根据实际需求配置城市坐标）
	const getCityLocation = (cityName) => {
		// 默认城市坐标映射
		const cityLocations = {
			'焦作市': { latitude: 35.215893, longitude: 113.241823 },
			'北京市': { latitude: 39.904989, longitude: 116.405285 },
			'上海市': { latitude: 31.230416, longitude: 121.473701 },
			'广州市': { latitude: 23.129112, longitude: 113.264385 },
			'深圳市': { latitude: 22.543099, longitude: 114.057868 },
			'杭州市': { latitude: 30.274084, longitude: 120.155070 },
			'南京市': { latitude: 32.041544, longitude: 118.767413 },
			'武汉市': { latitude: 30.592849, longitude: 114.305393 },
			'成都市': { latitude: 30.662420, longitude: 104.063321 },
			'西安市': { latitude: 34.341568, longitude: 108.940175 },
			'重庆市': { latitude: 29.563009, longitude: 106.551556 },
			'天津市': { latitude: 39.343357, longitude: 117.200983 },
			'郑州市': { latitude: 34.746611, longitude: 113.625368 },
			'周口市': { latitude: 33.630000, longitude: 114.650000 },
			'洛阳市': { latitude: 34.619689, longitude: 112.454040 }
		}
		
		return cityLocations[cityName] || { latitude: 34.825817, longitude: 113.55852 }
	}

	// 页面加载时获取当前位置
	onLoad(() => {
		const savedLocation = getLocation()
		if (savedLocation && savedLocation.city) {
			currentCity.value = savedLocation.city
		} else {
			// 如果没有保存的位置，尝试获取当前位置
			relocate()
		}
	})
</script>

<style scoped>
	/* 导航栏内容样式 */
	.navbar-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 88rpx;
		position: relative;
		margin: 0 -24rpx;
		padding: 0 24rpx;
	}

	.nav-left {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 60rpx;
		height: 88rpx;
	}

	.back-icon {
		color: #fff;
		font-size: 56rpx;
		font-weight: 300;
		line-height: 88rpx;
		transform: scaleY(1.3);
		cursor: pointer;
	}

	.nav-title {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		text-align: center;
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
		line-height: 88rpx;
	}

	.nav-right {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		gap: 16rpx;
		height: 88rpx;
	}

	.nav-icon-dots {
		color: #fff;
		font-size: 48rpx;
		line-height: 88rpx;
		font-weight: 300;
		transform: rotate(90deg);
	}

	.nav-divider {
		width: 2rpx;
		height: 32rpx;
		background-color: rgba(255, 255, 255, 0.7);
	}

	.nav-icon-target {
		width: 40rpx;
		height: 40rpx;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.target-outer {
		width: 36rpx;
		height: 36rpx;
		border: 2rpx solid #fff;
		border-radius: 50%;
		position: absolute;
	}

	.target-inner {
		width: 12rpx;
		height: 12rpx;
		background-color: #fff;
		border-radius: 50%;
		position: absolute;
	}

	/* 当前定位区域 */
	.current-location-section {
		background-color: #fff;
		padding: 24rpx 40rpx;
		display: flex;
		align-items: center;
		gap: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.location-label {
		font-size: 28rpx;
		color: #333;
	}

	.location-city {
		font-size: 28rpx;
		color: #2575fc;
		font-weight: 500;
		flex: 1;
	}

	.relocate-btn {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.relocate-icon {
		font-size: 32rpx;
		color: #2575fc;
	}

	.relocate-text {
		font-size: 24rpx;
		color: #2575fc;
	}

	/* 主要内容区域 */
	.content-section {
		background-color: #fff;
		min-height: calc(100vh - 300rpx);
		padding: 40rpx 30rpx;
		padding-bottom: 160rpx; /* 为底部按钮留出空间 */
	}

	/* 热门城市区域 */
	.popular-cities-section {
		margin-bottom: 60rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 24rpx;
		display: block;
	}

	.cities-grid {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.city-tag {
		background-color: #f5f5f5;
		border-radius: 40rpx;
		padding: 16rpx 32rpx;
		font-size: 28rpx;
		color: #333;
		min-width: 140rpx;
		text-align: center;
		transition: all 0.3s;
	}

	.city-tag-selected {
		background-color: #2575fc;
		color: #fff;
	}

	/* 城市列表区域 */
	.cities-list-section {
		padding-top: 20rpx;
	}

	.city-group {
		margin-bottom: 40rpx;
	}

	.group-letter {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}

	.city-items {
		background-color: #fff;
	}

	.city-item {
		display: flex;
		align-items: center;
		height: 88rpx;
		position: relative;
		transition: background-color 0.3s;
	}

	.city-item-selected {
		background-color: #f0f7ff;
	}

	.city-name {
		font-size: 28rpx;
		color: #333;
		flex: 1;
		transition: color 0.3s;
	}

	.city-name-selected {
		color: #2575fc;
		font-weight: 500;
	}
	
	/* 确认选择按钮区域（列表底部） */
	.confirm-section-list {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx 30rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		background-color: #fff;
		box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);
		z-index: 100;
	}

	.confirm-section-list .confirm-btn {
		width: 100%;
		height: 88rpx;
		background: linear-gradient(90deg, #2575fc, #6a11cb);
		color: #fff;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: bold;
		border: none;
		box-shadow: 0 4rpx 12rpx rgba(37, 117, 252, 0.3);
	}

	.city-divider {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 1rpx;
		background-color: #f0f0f0;
	}
</style>
